package com.flashcash.solu.view.certification.presenter;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;

import com.flashcash.solu.R;
import com.flashcash.solu.app.base.presenter.BaseActivityPresenterImpl;
import com.flashcash.solu.bean.ContactInfoBean;
import com.flashcash.solu.bean.ResponseErrorBody;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.view.certification.ContactInfoView;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.x.leo.apphelper.log.XLog;

import okhttp3.ResponseBody;
import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * @作者:My
 * @创建日期: 2017/6/21 13:32
 * @描述:${TODO}
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 */

public class ContactInfoActPreImp extends BaseActivityPresenterImpl implements ContactInfoActPresenter {
    @Override
    public void requestPermission() {
        new RxPermissions(mView.getBaseActivity())
                .request(new String[]{Manifest.permission.READ_CONTACTS})
                .subscribe(new Subscriber<Boolean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        XLog.INSTANCE.e("request contacts permission error:", throwable, 100);
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {

//                        StoreUtils.saveAll(mView.getBaseActivity());
                        if (aBoolean) {
                        } else {
                            new AlertDialog.Builder(mView.getBaseActivity())
                                    .setTitle(R.string.tips_title)
                                    .setCancelable(false)
                                    .setMessage(String.format(mView.getBaseActivity().getString(R.string.need_permission), Manifest.permission.READ_CONTACTS.replace("android.permission.", "")))
                                    .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            mView.getBaseActivity().setResult(Activity.RESULT_CANCELED);
                                            mView.getBaseActivity().finish();
                                        }
                                    })
                                    .show();
                        }
                    }
                });

    }

    @Override
    public void requestDatas() {
        showLoading(null);
        mUserApi.getContactInfo(TokenManager.getInstance().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ContactInfoBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                        XLog.INSTANCE.e("Get ContactInfo Failed: " , e,100);
                        XLeoToast.showMessage(R.string.show_get_contactinfo_fail);
                    }

                    @Override
                    public void onNext(ContactInfoBean contactInfoBean) {
                        dismissLoading();
                        if (isAttached() && contactInfoBean != null) {
                            ((ContactInfoView) mView).initView(contactInfoBean);
                        }
                    }
                });
    }

    @Override
    public void submitConatctInfo(String parentName, String parentPhone, String friendName, String friendPhone) {
        showLoading(null);
        mUserApi.submitContactInfo(parentName
                , parentPhone
                , friendName
                , friendPhone
                , TokenManager.getInstance().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e != null && e instanceof HttpException && ((HttpException) e).response() != null && ((HttpException) e).response().errorBody() != null) {
                            try {
                                ResponseErrorBody responseErrorBody = new Gson().fromJson(((HttpException) e).response().errorBody().string(), ResponseErrorBody.class);
                                XLeoToast.showMessage("" + responseErrorBody.getMessage());
                            } catch (Exception e1) {
                                // Gson throws JsonSyntaxException & response.body throws IOException
                                XLog.INSTANCE.e("httpException obtain error:", e, 100);
                                XLeoToast.showMessage(e.getMessage());
                            }
                        } else {
                            if (e != null) {
                                XLeoToast.showMessage(e.getMessage());
                            }
                        }
                        dismissLoading();
                        XLog.INSTANCE.e("e:" , e,100);

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        XLog.INSTANCE.d("Submit success!",10);
                        dismissLoading();
                        if (isAttached()) {
                            ((ContactInfoView) mView).onSubmitSuccess();
                        }
                    }
                });
    }
}
